import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

# 模拟数据
df = pd.read_csv(".\\data\\table8_1.csv", header=0, usecols=(0, 2))
X = df.to_numpy()
print(X)
# 特征标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# K-Means 聚类
kmeans = KMeans(n_clusters=3, random_state=42)
labels = kmeans.fit_predict(X_scaled)

# # 为了显示中文，指定默认字体
plt.rcParams["font.sans-serif"] = ["SimHei"]
# 可视化结果
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap="viridis", s=100, label="学生")
centers = scaler.inverse_transform(kmeans.cluster_centers_)  # 将聚类中心还原到原始尺度
plt.scatter(centers[:, 0], centers[:, 1], c="red", s=200, marker="X", label="聚类中心")

plt.xlabel("每天平均学习时长（小时）")
plt.ylabel("每天平均游戏时长（小时）")
plt.title("学生行为聚类分析（K-Means）")
plt.legend()
plt.grid(True)
plt.show()
